package com.siyoumi.config;

import com.siyoumi.util.XLog;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Slf4j
@Configuration
public class RedisConfig {
    //@Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> getRedis(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        //参照StringRedisTemplate内部实现指定序列化器
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        log.info("redis init");
        //XLog.info(this.getClass(), redisConnectionFactory.getConnection().info());
        return redisTemplate;
    }

    @Autowired
    private RedissonConfig redissonConfig;

    @Bean(destroyMethod = "shutdown", name = "redisson")
    public RedissonClient getRedisson() {
        //XLog.debug(this.getClass(), redissonConfig);
        if (XStr.isNullOrEmpty(redissonConfig.getAddress())) {
            log.error("redisson config miss");
            return null;
        }

        Config config = new Config();
        config.useSingleServer()
                .setAddress(redissonConfig.getAddress())
                .setPassword(redissonConfig.getPassword())
                .setDatabase(redissonConfig.getDatabase())
                .setTimeout(redissonConfig.getTimeout());
        config.setCodec(StringCodec.INSTANCE);

        log.info("redisson begin");
        return Redisson.create(config);
    }
}
